import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_category.dart';
import 'package:flutter_learn_vi/src/bean/bean_rank.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/page/common/common_loading_dialog.dart';
import 'package:flutter_learn_vi/src/page/common/common_nodata_widget.dart';
import 'package:flutter_learn_vi/src/utils/date_utils.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/string_utils.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';

import 'mine_my_his_page.dart';
import 'mine_my_score_model.dart';

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/13.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
///代码清单
class MineMyScoreItemLevelPage extends StatefulWidget {
  final CategoryItemBean categoryItemBean;
  final String categoryOne;
  final StreamController<String> dateSelectStream;

  MineMyScoreItemLevelPage(
      {@required this.categoryOne,
      @required this.categoryItemBean,
      Key key,
      this.dateSelectStream})
      : super(key: key);

  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<MineMyScoreItemLevelPage> {
  bool _isLoading = true;

  StreamSubscription _streamSubscription;

  @override
  void initState() {
    super.initState();
    _currentSelectDate = myScoreCurrentSelectDate;
    if (StringUtils.isEmpty(_currentSelectDate)) {
      _currentSelectDate =
          ViDateUtils.formatDate(DateTime.now(), format: "yyyy-MM");
      LogUtils.e("我的积分记录查询时间 $_currentSelectDate");
    }

    getMyScoreDataFunction();
    if (widget.dateSelectStream != null) {
      _streamSubscription = widget.dateSelectStream.stream.listen((event) {
        ToastUtils.showToast("正在刷新数据");
        _currentSelectDate = event;
        getMyScoreDataFunction();
      });
    }
  }

  @override
  void dispose() {
    if (_streamSubscription != null) {
      _streamSubscription.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) {
      return LoadingWidget();
    }
    if (_monthStatisticItemBean == null ||
        _monthStatisticItemBean.monthStatistics == null) {
      return NoDataWidget(
        clickCallBack: () async {
          setState(() {
            _isLoading = true;
          });
          await getMyScoreDataFunction();
          ToastUtils.showToast("已刷新");
        },
      );
    }

    return RefreshIndicator(
      notificationPredicate: (ScrollNotification notifation) {
        //该属性包含当前ViewPort及滚动位置等信息
        ScrollMetrics scrollMetrics = notifation.metrics;
        if (scrollMetrics.minScrollExtent == 0) {
          return true;
        } else {
          return false;
        }
      },
      onRefresh: () async {
        await getMyScoreDataFunction();
        ToastUtils.showToast("已刷新");
        return true;
      },
      child: NestedScrollView(
        body: Card(
          child: Container(
            child: MineMyScoreHisPage(
              categoryOne: widget.categoryOne,
              categoryItemBean: widget.categoryItemBean,
              monthStatisticItemBean: _monthStatisticItemBean,
              dateSelectStream: widget.dateSelectStream,
            ),
            margin: EdgeInsets.all(4),
          ),
          elevation: 2.0,
        ),
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverToBoxAdapter(
              child: buildAvgScoreWidget(),
            ),
          ];
        },
      ),
    );
  }

  //平均分
  Widget buildAvgScoreWidget() {
    return Card(
      elevation: 2.0,
      child: Container(
        width: double.infinity,
        padding: EdgeInsets.all(20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ClipOval(
              child: Container(
                alignment: Alignment.center,
                color: Colors.blueGrey.withOpacity(0.2),
                width: 96,
                height: 96,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      "${_monthStatisticItemBean.monthStatistics.averageScore ~/ 10}",
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 22,
                      ),
                    ),
                    Text(
                      "平均分",
                      style: TextStyle(
                        fontWeight: FontWeight.w400,
                        fontSize: 12,
                      ),
                    )
                  ],
                ),
              ),
            ),
            SizedBox(
              height: 16,
            ),
            Text("累计答题次数"),
            SizedBox(
              height: 6,
            ),
            Text(
              "${_monthStatisticItemBean.monthStatistics.extractingTimes}次",
              style: TextStyle(color: Colors.blueGrey),
            ),
          ],
        ),
      ),
    );
  }

  MonthStatisticItemBean _monthStatisticItemBean;
  String _currentSelectDate;

  Future<bool> getMyScoreDataFunction() async {
    Map<String, dynamic> monthMap = {
      "categoryOne": widget.categoryOne,
      "categoryTwo": widget.categoryItemBean.categoryCode,
      "sort": "TIMES",
      "date": "$_currentSelectDate-01 00:00:00"
    };
    //答题数据
    ResponseInfo statisRresponseInfo = await DioUtils.instance.getRequest(
      url: HttpHelper.questionmonthstatistics,
      queryParameters: monthMap,
    );

    if (statisRresponseInfo.success) {
      var responseData = statisRresponseInfo.data;
      if (responseData != null) {
        _monthStatisticItemBean = MonthStatisticItemBean.fromJson(responseData);
      }
    }
    _isLoading = false;

    if (mounted) {
      setState(() {});
    }

    return Future.value(true);
  }
}
